package com.ruoyi.cloudsyncuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cloudsyncuser.dto.UserRegistrationRequest;
import com.ruoyi.cloudsyncuser.model.User;
import com.ruoyi.cloudsyncuser.service.UserService;
import com.ruoyi.cloudsyncuser.mapper.UserMapper;
import com.ruoyi.cloudsyncuser.utils.AliMSUtils;
import com.ruoyi.cloudsyncuser.utils.BaseResult;
import com.ruoyi.cloudsyncuser.utils.DateUtil;
import com.ruoyi.cloudsyncuser.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public BaseResult sendCode(String phoneNumber) {
        try {
            String code = AliMSUtils.sendMessage(phoneNumber);
            redisTemplate.opsForValue().set("verificationCode:" + phoneNumber, code, 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return BaseResult.successResult();
    }

    public Boolean verifyCode(String phoneNumber, String code) {
        String redisCode = redisTemplate.opsForValue().get("verificationCode:" + phoneNumber);
        if (redisCode == null) {
            System.out.println("验证码已过期或不存在");
            return false;
        } else if (!redisCode.equals(code)) {
            System.out.println("验证码校验错误");
            return false;
        } else {
            redisTemplate.delete("verificationCode:" + phoneNumber);
            return true;
        }
    }

    public BaseResult loginByPwd(String username, String password) {
        BaseResult baseResult = BaseResult.successResult();
        Map<String, Object> data = new HashMap<>();
        // 使用 lambdaQuery 查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        if (user == null) {
            baseResult.setSuccess(false);
            baseResult.setMsg("用户不存在");
            return baseResult;
        }
        // 直接比对密码
        if (!password.equals(user.getPassword())) {
            baseResult.setSuccess(false);
            baseResult.setMsg("密码错误");
            return baseResult;
        }
        String userToken = JwtUtils.generateJwtFromUser(user);
        // 登录成功，返回用户信息
        data.put("msg", "登录成功");
        data.put("token", userToken);
        baseResult.setData(data);
        return baseResult;
    }


    public BaseResult loginByTel(String phoneNumber, String code) {
        BaseResult baseResult = BaseResult.successResult();
        Map<String, Object> data = new HashMap<>();
        if (verifyCode(phoneNumber, code)) {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getPhoneNumber, phoneNumber));
            if (user == null) {
                baseResult.setSuccess(false);
                baseResult.setMsg("用户不存在");
                return baseResult;
            }
            String userToken = JwtUtils.generateJwtFromUser(user);
            // 登录成功，返回用户信息
            data.put("msg", "登录成功");
            data.put("token", userToken);
            baseResult.setData(data);
            return baseResult;
        }
        data.put("msg", "登录失败");
        baseResult.setData(data);
        return baseResult;
    }


    public BaseResult registerUser(UserRegistrationRequest requestUser, String clientIp) {
        if (verifyCode(requestUser.getPhoneNumber(), requestUser.getCode())) {
            BaseResult baseResult = BaseResult.successResult();
            Map<String, Object> data = new HashMap<>();

            User user = new User();
            user.setUsername(requestUser.getUsername());
            user.setPhoneNumber(requestUser.getPhoneNumber());
            user.setPassword(requestUser.getPassword()); // 请确保密码加密
            user.setRegisterTime(new Date());
            user.setStatus(1); // 假设默认状态为正常
            user.setLoginTime(DateUtil.getCurrentDateTime());
            user.setLoginIp(clientIp);

            int insert = userMapper.insert(user);
            if (insert != 0) {
                data.put("msg", "用户注册成功");
            } else {
                data.put("msg", "用户注册失败");
            }
            baseResult.setData(data);
            return baseResult;
        } else {
            return BaseResult.exceptionResult();
        }
    }

    public BaseResult verifyToken(String token) {
        BaseResult baseResult = BaseResult.successResult();
        Map<String, Object> data = new HashMap<>();
        try {
            Claims claims = JwtUtils.parseJWT(token);
            data.put("claims",claims);
            baseResult.setData(data);
            return baseResult;  // 返回解析后的 claims 数据
        } catch (Exception e) {
            return BaseResult.tokenExpiredResult();
        }
    }
}
